var arrayToArray = function(inputArray, limit) {
    if (Array.isArray(inputArray)) return inputArray;
    if (Symbol.iterator in Object(inputArray)) return function(iterable, limit) {
        var resultArray = [], shouldContinue = true, errorOccurred = false, error = void 0;
        try {
            for (var iterator, step; !(shouldContinue = (step = iterable[Symbol.iterator]()).next().done) && (resultArray.push(step.value), 
            !limit || resultArray.length !== limit); shouldContinue = true) ;
        } catch (err) {
            errorOccurred = true, error = err;
        } finally {
            try {
                !shouldContinue && step.return && step.return();
            } finally {
                if (errorOccurred) throw error;
            }
        }
        return resultArray;
    }(inputArray, limit);
    throw new TypeError("Invalid attempt to destructure non-iterable instance");
}, e = require("../common/component"), i = require("../mixins/touch");

(0, e.VantComponent)({
    mixins: [ i.touch ],
    classes: [ "nav-class", "tab-class", "tab-active-class", "line-class" ],
    relation: {
        name: "tab",
        type: "descendant",
        linked: function(t) {
            this.child.push(t), this.updateTabs(this.data.tabs.concat(t.data));
        },
        unlinked: function(t) {
            var e = this.child.indexOf(t), i = this.data.tabs;
            i.splice(e, 1), this.child.splice(e, 1), this.updateTabs(i);
        }
    },
    props: {
        tabColor: String,
        isSticky: Boolean,
        isAnimated: Boolean,
        isSwipeable: Boolean,
        lineWidth: {
            type: Number,
            value: -1
        },
        lineHeight: {
            type: Number,
            value: -1
        },
        activeTabIndex: {
            type: Number,
            value: 0
        },
        tabType: {
            type: String,
            value: "line"
        },
        hasBorder: {
            type: Boolean,
            value: true
        },
        transitionDuration: {
            type: Number,
            value: .3
        },
        zIndexLevel: {
            type: Number,
            value: 1
        },
        swipeThreshold: {
            type: Number,
            value: 4
        },
        offsetTop: {
            type: Number,
            value: 0
        }
    },
    data: {
        tabsData: [],
        lineStyle: "",
        scrollLeft: 0,
        isScrollable: false,
        trackStyle: "",
        wrapStyle: "",
        currentPosition: ""
    },
    watch: {
        swipeThreshold: function() {
            this.set({
                isScrollable: this.child.length > this.data.swipeThreshold
            });
        },
        tabColor: "setLineStyle",
        lineWidth: "setLineStyle",
        lineHeight: "setLineStyle",
        activeTabIndex: "setActiveTab",
        isAnimated: "setTrackStyle",
        offsetTop: "setWrapStyle"
    },
    beforeCreate: function() {
        this.child = [];
    },
    mounted: function() {
        var t = this;
        this.setLine(!0), this.setTrack(), this.scrollIntoView(), this.getRect(".van-tabs__wrap").then(function(e) {
            t.navHeight = e.height, t.observerContentScroll();
        });
    },
    destroyed: function() {
        this.createIntersectionObserver().disconnect();
    },
    methods: {
        updateTabs: function(updatedTabs) {
            updatedTabs = updatedTabs || this.data.tabsData, this.set({
                tabsData: updatedTabs,
                isScrollable: updatedTabs.length > this.data.swipeThreshold
            }), this.setActiveTab();
        },
        triggerEvent: function(eventName, index) {
            this.$emit(eventName, {
                index: index,
                title: this.data.tabsData[index].title
            });
        },
        handleTap: function(event) {
            var tabIndex = event.currentTarget.dataset.index;
            this.data.tabsData[tabIndex].disabled ? this.triggerEvent("disabled", tabIndex) : (this.triggerEvent("click", tabIndex), 
            this.setActive(tabIndex));
        },
        setActiveTabByIndex: function(newIndex) {
            newIndex !== this.data.activeTabIndex && (this.triggerEvent("change", newIndex), this.set({
                activeTabIndex: newIndex
            }), this.setActiveTab());
        },
        setLineStyle: function(isInitial) {
            var self = this;
            if ("line" === this.data.tabType) {
                var componentData = this.data, color = componentData.tabColor, activeIndex = componentData.activeTabIndex, duration = componentData.transitionDuration, lineWidth = componentData.lineWidth, lineHeight = componentData.lineHeight;
                this.getRect(".van-tab", true).then(function(tabRects) {
                    var activeTabRect = tabRects[activeIndex], lineHalfWidth = -1 !== lineWidth ? lineWidth : activeTabRect.width / 2, lineHeightStyle = -1 !== lineHeight ? "height: " + lineHeight + "px;" : "", accumulatedWidth = tabRects.slice(0, activeIndex).reduce(function(totalWidth, tabRect) {
                        return totalWidth + tabRect.width;
                    }, 0);
                    accumulatedWidth += (activeTabRect.width - lineHalfWidth) / 2;
                    var transitionStyle = isInitial ? "" : "transition-duration: " + duration + "s; -webkit-transition-duration: " + duration + "s;";
                    self.set({
                        lineStyle: "\n            " + lineHeightStyle + "\n            width: " + lineHalfWidth + "px;\n            background-color: " + color + ";\n            -webkit-transform: translateX(" + accumulatedWidth + "px);\n            transform: translateX(" + accumulatedWidth + "px);\n            " + transitionStyle + "\n          "
                    });
                });
            }
        },
        setTrackStyle: function() {
            var self = this, componentData = this.data, isAnimated = componentData.isAnimated, activeIndex = componentData.activeTabIndex, duration = componentData.transitionDuration;
            if (!isAnimated) return "";
            this.getRect(".van-tabs__content").then(function(contentRect) {
                var contentWidth = contentRect.width;
                self.set({
                    trackStyle: "\n            width: " + contentWidth * self.child.length + "px;\n            left: " + -1 * activeIndex * contentWidth + "px;\n            transition: left " + duration + "s;\n            display: -webkit-box;\n            display: flex;\n          "
                });
                var childProps = {
                    width: contentWidth,
                    animated: isAnimated
                };
                self.child.forEach(function(child) {
                    child.set(childProps);
                });
            });
        },
        setActiveTab: function() {
            var self = this;
            this.child.forEach(function(child, index) {
                var childProps = {
                    active: index === self.data.activeTabIndex
                };
                childProps.active && (childProps.inited = true), childProps.active !== child.data.active && child.set(childProps);
            }), this.set({}, function() {
                self.setLineStyle(), self.setTrackStyle(), self.scrollIntoView();
            });
        },
        scrollIntoView: function() {
            var self = this, componentData = this.data, activeIndex = componentData.activeTabIndex;
            componentData.isScrollable && Promise.all([ this.getRect(".van-tab", true), this.getRect(".van-tabs__nav") ]).then(function(rects) {
                var arrayResult = arrayToArray(rects, 2), tabRects = arrayResult[0], navRect = arrayResult[1], activeTabRect = tabRects[activeIndex], accumulatedWidth = tabRects.slice(0, activeIndex).reduce(function(totalWidth, tabRect) {
                    return totalWidth + tabRect.width;
                }, 0);
                self.set({
                    scrollLeft: accumulatedWidth - (navRect.width - activeTabRect.width) / 2
                });
            });
        },
        handleTouchStart: function(event) {
            this.data.isSwipeable && this.touchStart(event);
        },
        handleTouchMove: function(event) {
            this.data.isSwipeable && this.touchMove(event);
        },
        handleTouchEnd: function() {
            if (this.data.isSwipeable) {
                var componentData = this.data, activeIndex = componentData.activeTabIndex, tabsData = componentData.tabsData, swipeDirection = this.direction, swipeDeltaX = this.deltaX, swipeOffsetX = this.offsetX;
                "horizontal" === swipeDirection && 50 <= swipeOffsetX && (0 < swipeDeltaX && 0 !== activeIndex ? this.setActiveTabByIndex(activeIndex - 1) : swipeDeltaX < 0 && activeIndex !== tabsData.length - 1 && this.setActiveTabByIndex(activeIndex + 1));
            }
        },
        setWrapStyle: function() {
            var componentData = this.data, topOffset = componentData.offsetTop, wrapStyle = void 0;
            switch (componentData.currentPosition) {
              case "top":
                wrapStyle = "\n            top: " + topOffset + "px;\n            position: fixed;\n          ";
                break;

              case "bottom":
                wrapStyle = "\n            top: auto;\n            bottom: 0;\n          ";
                break;

              default:
                wrapStyle = "";
            }
            wrapStyle !== this.data.wrapStyle && this.set({
                wrapStyle: wrapStyle
            });
        },
        observerContentScroll: function() {
            var self = this;
            if (this.data.isSticky) {
                var topOffset = this.data.offsetTop, windowHeight = wx.getSystemInfoSync().windowHeight;
                this.createIntersectionObserver().disconnect(), this.createIntersectionObserver().relativeToViewport({
                    top: -(this.navHeight + topOffset)
                }).observe(".van-tabs", function(intersectionInfo) {
                    var boundingClientRect = intersectionInfo.boundingClientRect, topPosition = boundingClientRect.top;
                    if (!(topOffset < topPosition)) {
                        var intersectionRatio = intersectionInfo.intersectionRatio, newPosition = 0 < intersectionRatio ? "top" : "bottom";
                        self.$emit("scroll", {
                            scrollTop: topPosition + topOffset,
                            isFixed: "top" === newPosition
                        }), self.setPosition(newPosition);
                    }
                }), this.createIntersectionObserver().relativeToViewport({
                    bottom: -(windowHeight - 1 - topOffset)
                }).observe(".van-tabs", function(intersectionInfo) {
                    var boundingClientRect = intersectionInfo.boundingClientRect, topPosition = boundingClientRect.top;
                    if (!(boundingClientRect.bottom < this.navHeight)) {
                        var intersectionRatio = intersectionInfo.intersectionRatio, newPosition = 0 < intersectionRatio ? "top" : "";
                        self.$emit("scroll", {
                            scrollTop: topPosition + topOffset,
                            isFixed: "top" === newPosition
                        }), self.setPosition(newPosition);
                    }
                });
            }
        },
        setPosition: function(newPosition) {
            var self = this;
            newPosition !== this.data.currentPosition && this.set({
                currentPosition: newPosition
            }).then(function() {
                self.setWrapStyle();
            });
        }
    }
});